package leetcode;

/**
 * @program: datastructureandalogorithm
 * @description:
 * @author: hmx
 * @create: 2021-10-22 08:48
 **/
public class LeetCode2 {
    public ListNode addTwoNumbers2(ListNode l1, ListNode l2) {
        //返回的新头结点
        ListNode head = new ListNode();
        ListNode temp = head;
        //用来存储需要进的位
        int n = 0;
        while (l1 != null || l2 != null) {
            //l1节点是否为空
            boolean flag1 = l1 == null;
            //l2节点是否为空
            boolean flag2 = l2 == null;
            int a = flag1 ? 0 : l1.val;
            int b = flag2 ? 0 : l2.val;
            int sum = a + b;
            boolean flag = (sum + n) / 10 == 1;
            if (flag) {
                temp.val = (sum + n) % 10;
                n = 1;
            } else {
                temp.val = sum + n;
                n = 0;
            }
            if (!flag1) {
                l1 = l1.next;
            }
            if (!flag2) {
                l2 = l2.next;
            }

            if (l1 == null && l2 == null && n == 1) {
                temp.next = new ListNode(1);
                break;
            } else if (l1 == null && l2 == null) {
                break;
            }
            temp.next = new ListNode();
            temp = temp.next;
        }
        return head;
    }


}
